package org.lansir.af.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.lansir.af.R;
import org.lansir.af.database.DataRowActivity;
import org.lansir.af.database.DataRowActivityParticipator;
import org.lansir.af.database.DataTable;
import org.lansir.af.database.Database;
import org.lansir.af.dataview.DataView;
import org.lansir.af.dataview.DataViewActivity;
import org.lansir.af.dataview.DataViewItem;
import org.lansir.af.dataview.DataViewItemActivity;
import org.lansir.af.dataview.DataViewItemActivityComparator;
import org.lansir.af.model.CalendarKey;
import org.lansir.af.ui.widget.ActivityListItemContentLayout;
import org.lansir.af.util.Utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ScheduleFragment extends CommonFragment {
	private static final String TAG = "ScheduleFragment";
	
	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("org.lansir.af", "org.lansir.af.gtalk.GtalkService"));
	}
	
	private DataViewActivity dataViewActivity;
	protected Calendar dateToday = Calendar.getInstance();
	private DataViewItemActivityComparator rowComparator;
	protected Map<CalendarKey, List<DataViewItem>> mapDayRowsForView = new HashMap<CalendarKey, List<DataViewItem>>();
	private ActivityListItemContentLayout allayActivityListItemContent = null;
	private LayoutInflater mInflater;
	private LinearLayout llayAgendaDataList;
	private ImageView ivNoActivityList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		dataViewActivity = new DataViewActivity(this.userdb);

		reloadSchedule();
		dataViewActivity.filterData(getDateToday(), ViewType.WEEK);

		setHasOptionsMenu(true);
		rowComparator = new DataViewItemActivityComparator();
		addDataToMap(dataViewActivity);

		sortMapView();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View viewRoot = inflater.inflate(R.layout.fragment_schedule, null);
		llayAgendaDataList = (LinearLayout) viewRoot.findViewById(R.id.llayActivityList);
		ivNoActivityList = (ImageView) viewRoot.findViewById(R.id.ivNoActivityList);
		mInflater = inflater;
		CalendarKey calKey = new CalendarKey(dateToday);
		boolean hasActivity = false;
		for (int i = 0; i < 7; i++) {
			// Log.v("ActivityFairy", "CalKey:" + calKey.getMonth() + ",day:" +
			// calKey.getDay());
			if (mapDayRowsForView.get(calKey) != null) {
				hasActivity = true;
				View v = addActivityItem(calKey, mapDayRowsForView.get(calKey));
				llayAgendaDataList.addView(v);
			}
			calKey.addDay();
		}
		if(!hasActivity){
			ivNoActivityList.setVisibility(View.VISIBLE);
		}
		return viewRoot;
	}

	protected void reloadSchedule() {
		if (userdb.databaseReady()) {
			dataViewActivity.reloadTable();
			// Log.v(Database.TAG, "realoadTable:" + flag);
		}
	}

	// refresh start view date
	public synchronized void updateTodayDate() {
		dateToday.setTimeInMillis(System.currentTimeMillis());
		dateToday.setFirstDayOfWeek(Calendar.MONDAY);
	}

	public Calendar getDateToday() {
		return dateToday;
	}

	public Calendar latestDateToday() {
		updateTodayDate();
		return getDateToday();
	}

	/**
	 * 把数据加入HashMap
	 * 
	 * @param dataView
	 */
	private void addDataToMap(DataView dataView) {
		List<DataViewItem> rows = dataView.getRowsForView();
		// Log.v("ActivityFairy", "AgendaViewActivity:rebuildViewItems:" +
		// rows.size());
		mapDayRowsForView.clear();

		for (int i = 0; i < rows.size(); i++) {
			DataViewItemActivity dataViewItemActivity = (DataViewItemActivity) rows.get(i);
			if (dataViewItemActivity.isRepeat()) {
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(getDateToday().getTimeInMillis());
				for (int iDay = 0; iDay < 7; iDay++) {
					// get item visible date

					// Log.v("ActivityFairy", "DataViewItemActivity:" +
					// dataViewItemActivity.getSubject() + ":DayOfWeek:" +
					// cal.get(Calendar.DAY_OF_WEEK));
					if (dataViewItemActivity.getVisibleDay(iDay)) {
						// get week day item
						// Log.v("ActivityFairy", "DataViewItemActivity:" +
						// dataViewItemActivity.getSubject() + ":Visiable");
						CalendarKey tmpKey = new CalendarKey(cal);
						List<DataViewItem> tmpDataViewItemList = mapDayRowsForView.get(tmpKey);
						if (tmpDataViewItemList == null) {
							tmpDataViewItemList = new ArrayList<DataViewItem>();
							mapDayRowsForView.put(tmpKey, tmpDataViewItemList);
						}
						tmpDataViewItemList.add(dataViewItemActivity);
					}
					cal.add(Calendar.DAY_OF_YEAR, 1);

				}
			} else {
				CalendarKey tmpKey = new CalendarKey(dataViewItemActivity.getStartDate());
				List<DataViewItem> tmpDataViewItemList = mapDayRowsForView.get(tmpKey);
				if (tmpDataViewItemList == null) {
					tmpDataViewItemList = new ArrayList<DataViewItem>();
					mapDayRowsForView.put(tmpKey, tmpDataViewItemList);
				}
				tmpDataViewItemList.add(dataViewItemActivity);
			}
		}
	}

	/**
	 * 对Map进行排序
	 */
	private void sortMapView() {

		for (Map.Entry<CalendarKey, List<DataViewItem>> entry : mapDayRowsForView.entrySet()) {
			List<DataViewItem> l = entry.getValue();

			Collections.sort(l, rowComparator);

			entry.setValue(l);
		}
	}

	private View addActivityItem(CalendarKey actDate, List<DataViewItem> dataViewItems) {
		View vActivityItem = mInflater.inflate(R.layout.fragment_schedule_listitem, null);
		TextView tvActivityDateRank = (TextView) vActivityItem.findViewById(R.id.tvActivityItemDateRank);
		TextView tvActivityDateWeek = (TextView) vActivityItem.findViewById(R.id.tvActivityItemDateWeek);
		TextView tvActivityItemDateMonth = (TextView) vActivityItem.findViewById(R.id.tvActivityItemDateMonth);
		TextView tvActivityItemDateDay = (TextView) vActivityItem.findViewById(R.id.tvActivityItemDateDay);

		LinearLayout llayActvityItemContent = (LinearLayout) vActivityItem.findViewById(R.id.llayActvityItemContent);
		try {
			tvActivityDateRank.setText(getResources().getStringArray(R.array.dayName)[actDate.getDayOfYear() - getDateToday().get(Calendar.DAY_OF_YEAR)]);
			tvActivityDateWeek.setText(getResources().getStringArray(R.array.weekName)[actDate.getDayOfWeek() - 1]);
		} catch (Exception e) {
			e.printStackTrace();
		}
		tvActivityItemDateMonth.setText((actDate.getMonth() + 1) + utils.getResStr(R.string.strActivityItemMonth));
		tvActivityItemDateDay.setText(""+actDate.getDay());

		for (DataViewItem dataItem : dataViewItems) {
			final DataViewItemActivity dataViewItemActivity = (DataViewItemActivity) dataItem;
			ActivityListItemContentLayout llayActivityItemContentLayout = (ActivityListItemContentLayout) mInflater.inflate(
					R.layout.fragment_schedule_listitem_content, null);
			// = new ActivityListItemContentLayout(main);//
			llayActivityItemContentLayout.setDataViewItemActivity(dataViewItemActivity);
			TextView tvActivityContentTitle = (TextView) llayActivityItemContentLayout.findViewById(R.id.tvActivityContentTitle);
			TextView tvActivityContentTime = (TextView) llayActivityItemContentLayout.findViewById(R.id.tvActivityContentTime);
			TextView tvActivityContentOrganier = (TextView) llayActivityItemContentLayout.findViewById(R.id.tvActivityContentOrganizer);
			ImageView ivActivityContentRepeat = (ImageView) llayActivityItemContentLayout.findViewById(R.id.ivActivityContentRepeat);
			ImageView ivActivityContentAlarm = (ImageView) llayActivityItemContentLayout.findViewById(R.id.ivActivityContentAlarm);

			tvActivityContentTitle.setText(dataViewItemActivity.getSubject());
			tvActivityContentTime.setText(utils.getTime(dataViewItemActivity.getStartDate()));
			tvActivityContentOrganier.setText(String.format(utils.getResStr(R.string.strAgendaActivityItemOrganizer), dataViewItemActivity.getOrganizer()));
			ivActivityContentRepeat.setVisibility(dataViewItemActivity.isRepeat() ? View.VISIBLE : View.GONE);
			ivActivityContentAlarm.setVisibility(dataViewItemActivity.isAlarm() ? View.VISIBLE : View.GONE);

			llayActivityItemContentLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					openActivityInfo(dataViewItemActivity.getId());
				}
			});
			llayActvityItemContent.addView(llayActivityItemContentLayout);
			//TODO
//			this.registerForContextMenu(llayActivityItemContentLayout);
		}

		return vActivityItem;
		// llayAgendaDataList.addView(vActivityItem);
	}

	private void openActivityInfo(long iActivityId) {
		this.bundleOtherDataStartup.putLong(CommonFragment.requestBundleRowId, iActivityId);
		this.openActivityForResult(CommonFragment.REQUEST_CODE_DEFAULT, "org.lansir.af.intent.action.ACTION_MODE_VIEW_ACTIVITYINFO");
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.schedule_menu_items, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_create) {
			openActivityForResult(0, "org.lansir.af.intent.action.ACTION_MODE_NEW_ACTIVITY");
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/*@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		if (v instanceof ActivityListItemContentLayout) {
			ActivityListItemContentLayout activityListItemContentLayout = (ActivityListItemContentLayout) v;
			allayActivityListItemContent = activityListItemContentLayout;
			MenuInflater inflater = getActivity().getMenuInflater();

			//TODO
//			if (activityListItemContentLayout.getDataViewItemActivity().getOrganizer().equals(utils.getResStr(R.string.strActivityOrganizerMe))) {
//				inflater.inflate(R.menu.schedule_activity_list_item_organizerme, menu);
//
//			} else {
				inflater.inflate(R.menu.schedule_activity_list_item_organizerother, menu);

//			}
			menu.setHeaderTitle(activityListItemContentLayout.getDataViewItemActivity().getSubject());

		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}*/

	/*@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuitem_agenda_activity_list_item_organizerme_view:
		case R.id.menuitem_agenda_activity_list_item_organizerother_view:
			bundleOtherDataStartup.putLong(CommonFragment.requestBundleRowId, allayActivityListItemContent.getDataViewItemActivity().getId());
			openActivityForResult(CommonFragment.REQUEST_CODE_DEFAULT, "org.lansir.af.intent.action.ACTION_MODE_VIEW_ACTIVITYINFO");
			break;
		case R.id.menuitem_agenda_activity_list_item_organizerme_edit:
			bundleOtherDataStartup.putLong(CommonFragment.requestBundleRowId, allayActivityListItemContent.getDataViewItemActivity().getId());
			openActivityForResult(CommonFragment.REQUEST_CODE_DEFAULT, "org.lansir.af.intent.action.ACTION_MODE_EDIT_ACTIVITY");
			break;
		case R.id.menuitem_agenda_activity_list_item_organizerme_delete:
			utils.showSelectDialog(R.string.strActivityInfoMsgDeleteSelfOrganizer, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (sendDeleteMessage()) {
						deleteActivityAndRefresh();
					}
				}

			}, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					deleteActivityAndRefresh();
				}

			}, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}

			});

			break;
		case R.id.menuitem_agenda_activity_list_item_organizerother_delete:
			utils.showConfirmDialog(R.string.strActivityInfoMsgDelete, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					deleteActivityAndRefresh();
				}

			}, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}

			});
			break;
		}
		return super.onContextItemSelected(item);
	}*/

	private boolean sendDeleteMessage() {

		return true;
	}

	private void deleteActivityAndRefresh() {
		DataRowActivity dataRowActivity = new DataRowActivity(this.userdb);
		DataTable dataTableActivity = new DataTable(dataRowActivity);
		DataRowActivityParticipator dataRowActivityParticipator = new DataRowActivityParticipator(this.userdb);
		DataTable dataTableActivityParticipator = new DataTable(dataRowActivityParticipator);
		Database.Result result = dataTableActivityParticipator.deleteData("ActivityID=" + allayActivityListItemContent.getDataViewItemActivity().getId());
		if (result != Database.Result.Success) {
			utils.showMsgResStr(Database.getErrDesc(result), Utils.MSGTYPE_ERROR);
		}
		result = dataTableActivity.deleteData(allayActivityListItemContent.getDataViewItemActivity().getId());
		if (result != Database.Result.Success) {
			utils.showMsgResStr(Database.getErrDesc(result), Utils.MSGTYPE_ERROR);
		} else {
			refreshData();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == Activity.RESULT_OK) {
			Bundle extras = data.getExtras();
			if (extras != null && extras.containsKey(CommonFragment.requestBundleTableUpdated)) {
				refreshData();

			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private void refreshData() {
		llayAgendaDataList.removeAllViews();
		reloadSchedule();
		dataViewActivity.filterData(getDateToday(), ViewType.WEEK);
		addDataToMap(dataViewActivity);
		sortMapView();
		CalendarKey calKey = new CalendarKey(dateToday);
		boolean hasActivity = false;
		for (int i = 0; i < 7; i++) {
			// Log.v("ActivityFairy", "CalKey:" + calKey.getMonth() + ",day:" +
			// calKey.getDay());
			if (mapDayRowsForView.get(calKey) != null) {
				hasActivity = true;
				View v = addActivityItem(calKey, mapDayRowsForView.get(calKey));
				llayAgendaDataList.addView(v);
			}
			calKey.addDay();
		}
		if(!hasActivity){
			ivNoActivityList.setVisibility(View.VISIBLE);
		}else{
			ivNoActivityList.setVisibility(View.GONE);
		}
	}


}
